<?php

namespace control;
/*
*结账
*/


use DateInterval;
use DatePeriod;
use DateTime;

class checkoutClass extends adIndexClass
{
    private const page  = 'checkout';
    private const title = '结账';
    private string $pass_ico = root . 'img/control/pass.svg';
    private string $no_pass_ico = root . 'img/control/no_pass.svg';
    private string $problem_ico = root . 'img/control/exclamation.svg';


    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow = '结账'): string
    {
        $html = hidden(array('name' => 'type', 'value' => $this->get('type'))) .
            hidden(array('name' => 'month', 'value' => $this->get('month'))) .
            hidden(array('name' => 'stage', 'value' => $this->get('stage') ?: 'first'));
        //生成查询表单
        return $this->search($html, 'menu', 'no');
    }

    /*列表-查询条件*/
    public function home($workFlow = '结账')
    {
        return $this->homeFun($this->homeForm($workFlow));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        if ($this->post('type') == 'stage') {
            $html = $this->settingSearch($this->post('stage'));
        } else {
            $html = $this->homeContent();
        }

        $html .= $this->style() . $this->js();
        //控件
        //返回
        $json['html'] = "<form name='listForm'>" . space . $html . "</form>" . space . clear;
        return json_encode($json, 320);
    }


    public function homeContent()
    {
        $company = query('company', "coid = '" . self::$coid . "'");
        $start   = new \DateTime($company['startDate'] . '-01');
        $end     = new \DateTime($this->date);
//        $end->modify('+1 month');
        $interval = DateInterval::createFromDateString('1 month');
        $period   = new DatePeriod($start, $interval, $end);
        $preYear  = '';//上一年
        $content  = '';
        $months   = [];
        foreach ($period as $k => $dt) {
            $months[] = $dt->format("Y-m");
        }
        $months = array_reverse($months);
        foreach ($months as $k => $val) {
            $monthText = date("m月", strtotime($val . '-01'));//当前月份
            $year      = date("Y", strtotime($val . '-01'));//当前年份
            $month     = date("Y-m", strtotime($val . '-01'));//当前月份
            $edit      = 1;
            //判断是否已结转了损益
            $borderClass     = 'yellow-border';
            $backgroundClass = 'yellow';
            if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format('%Y-%m',recordDate) = '$month' and source = '结转损益' and sourceId in (select id from period_end_setting where coid = '".self::$coid."' and type in ('结转损益（收入）','结转损益（费用）'))")) < 2) {
                if ($this->juageIsEndProfitAndLoss($month)) {
                    $borderClass     = 'blue-border';
                    $backgroundClass = 'blue';
                }
            }
            //判断是否已结账
            if (static::total(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "' and month = '$month'")) > 0) {
                $borderClass     = 'gray-border';
                $backgroundClass = 'gray';
                $edit            = 0;
            }
            if (empty($preYear) || $preYear != $year) {
                $content .= <<<eof
            <div class="period-content-year">
                <div><p><span class="year-font">{$year}年</span></p></div>
                <div class="row-item-ul">
eof;
            }
            $content .= <<<eof
                <div class="month-item row-item $borderClass" data-edit="$edit" data-month="$month">
                    <div class="row-item-top $backgroundClass"></div>
                    <div class="row-item-bottom">$monthText</div>
                </div>
eof;
            if (isset($months[$k + 1]) && $year != date('Y', strtotime($months[$k + 1] . '-01'))) {
                $content .= <<<eof
                 </div>
                </div>
eof;
            }
            $preYear = $year;
        }
        return <<<efo
<div style="padding: 0 10px">
    <div class="period-button">
<!--        <span class="spanButton" style="margin-left: 0">批量结账</span>-->
        <span><div class="dot yellow"></div>&nbsp;未结转损益，未结账</span>&emsp;&emsp;<span><div class="dot blue"></div>&nbsp;已结转损益，未结账</span>&emsp;&emsp;<span><div class="dot gray"></div>&nbsp;已结转损益，已结账</span>
    </div>
    <div class="period-content">
        $content
    </div>
</div>
efo;
    }

    /**
     * js
     * @return string
     */
    private function js(): string
    {
        return <<<eof
<script>
$(".month-item").on('click',function() {
    let month = $(this).data('month');
    let edit = $(this).data('edit');
    if (edit){
        newIframe('结账',root+'control/adIndex.html?cla=checkout&fun=home&type=stage&month='+month)
    }
})
</script>
eof;

    }

    /**
     * 结账
     * @param string $stage
     * @return string
     */
    public function settingSearch($stage = 'first'): string
    {
        $month    = $this->get('month');
        $stageOne = $stageTwo = $stageThree = '';
        if ($stage == 'first') {
            $stageOne = 'now-li';
        }
        if ($stage == 'second') {
            $stageTwo = 'now-li';
        }
        if ($stage == 'third') {
            $stageThree = 'now-li';
        }
        $html = <<<eof
<div class="progress-content">
    <div id="first" style="position: relative">
        <div class="progress-li $stageOne">1</div>
        <div class="progress-text">第一步：期末检查</div>
    </div>
    <div class="progress-li-line"></div>
    <div id="second" style="position: relative">
        <div class="progress-li $stageTwo">2</div>
        <div class="progress-text">第二步：结转损益</div>
    </div>
    <div class="progress-li-line"></div>
    <div id="third" style="position: relative">
        <div class="progress-li $stageThree">3</div>
        <div class="progress-text">第三步：结账</div>
    </div>
</div>
<div class="setting-content">

</div>
<div class="space"></div>
<div style="text-align: center;margin-top: 20px"><span id="preStage" class="spanButton" onclick="requsetStage(this)" data-operator="pre">上一步</span><span id="nextStage" onclick="requsetStage(this)" data-operator="next" class="spanButton li-btn-blue-bg">下一步</span></div>
<input name="stage" type="hidden" value="$stage">
<input name="month" type="hidden" value="$month">
eof;
        //控件
        return $html . $this->settingStyle() . $this->settingJs();
    }


    /**
     *
     * @return string
     */
    private function settingJs(): string
    {
        return <<<eof
<script>
$(function() {
  requsetStage();
})
    function requsetStage(e,stage='',operator=''){
        stage = stage?stage:$("[name='stage']").val();
        operator = operator?operator:$(e).data('operator');
        let month = $("[name='month']").val();
        if (stage ==='first' && operator ==='pre'){
            newIframe('结账',root+'control/adIndex.html?cla=checkout&fun=home')
            return false;
        }
          let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        if (stage ==='third' && operator ==='next'){
            //结账
             $.post(root+'control/adIndex.html?cla=checkout&fun=billEnd',{month:month},function(res) {
                  $("#loading", window.top.document).hide();
                    clearTimeout(con);
                 if (res.warn ==2){
                     location.href = res.href;
                 }else{
                     msg(res.warn,'error')
                 }
             },'json');
            return false;
        }
        $.post(root+'control/adIndex.html?cla=checkout&fun=stage',{stage:stage,operator:operator,month:month},function(res) {
             $("#loading", window.top.document).hide();
             clearTimeout(con);
              if (res.stage ==='second' && res.isFlush){
                   requsetStage(null,'first','next')
               }
            if (res.warn ==2){
                $(".setting-content").empty().append(res.html);
                $("[name='stage']").val(res.stage);
                if(res.stage ==='second'){
                      $("#second").children("div:first").addClass('now-li');
                      $("#third").children("div:first").removeClass('now-li');
                      $("#nextStage").html('下一步');
                    
                }else if(res.stage ==='third'){
                     $("#third").children("div:first").addClass('now-li');
                     $("#nextStage").html('结账')
                } else {
                     $("#nextStage").html('下一步')
                     $("#first").children("div:first").addClass('now-li');
                     $("#second").children("div:first").removeClass('now-li');
                     $("#third").children("div:first").removeClass('now-li');
                }
            }else{
                msg(res.warn,'error')
            }
            
        },'json')
    }
    
    //断号修复
    function repairVoucherNo(month){
       if (!month){
           msg('未找到月份','error');
           return false;
       }
       $.post(root+'control/adIndex.html?cla=voucher&fun=tidyEdit',{month:month,type:'100'},function(res) {
           if (res.warn ==2){
               location.reload();
           }else{
               msg(res.warn,'error')
           }
       },'json')
    }
    
</script>
eof;

    }


    public function stage()
    {
        $stage    = $this->post('stage');
        $operator = $this->post('operator');
        $month    = $this->post('month');
        if (empty($month)) {
            $json['warn'] = '未找到日期';
        } elseif (empty($stage)) {
            $json['warn'] = '未找到阶段';
        } else {
            $json['isFlush'] =0;
            $company  = query('company', "coid = '" . self::$coid . "'");
            $preMonth = date('Y-m', strtotime("-1 month", strtotime($month . '-01')));
            if ($operator == 'next') {
                switch ($stage) {
                    case 'first':
                        $stage = 'second';

                        break;
                    case 'second':
                        $this->startTrans();
                        $bool = $this->autoCreateIncome($month);
                        $json['stage'] = $stage;
                        if ($bool !==true){
                            $this->rollback();
                            $json['warn'] = '自动结转损益失败，请尝试手动结转';
//                            $json['warn'] = $bool;
                            goto resp;
                        }

                        $json['isFlush'] = 1;
                        $this->commitTrans();
                        $stage = 'third';
                        break;
                }
            } elseif ($operator == 'pre') {
                switch ($stage) {
                    case 'third':
                        $stage = 'second';
                        break;
                    case 'second':
                        $stage = 'first';
                        break;
                }
            }

            if ($stage == 'third' && !$this->juageIsEndProfitAndLoss($month)) {
                $json['warn'] = "请先结转损益";
            } elseif ($stage == 'third' && $month > $company['startDate'] && static::total(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "' and month = '$preMonth'")) == 0) {
                $json['warn'] = '由于上期还没有结账，无法进行下一步，请先将上期结账哦~';
            } else {
                switch ($stage) {
                    case 'second':
                        $li  = '';
                        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and type  in ('结转损益（收入）','结转损益（费用）') order by time asc"));
                        foreach ($all['array'] as $array) {
                            $money   = $this->calculateBalance($array['id'], $month);
                            $money   = number_format($money, 2);
                            $btn     = <<<eof
<span class="spanButton li-btn-blue-bg" onclick="newIframe('新增凭证',root+'control/adIndex.html?cla=voucherEdit&fun=home&method=endPeriod&sourceId={$array['id']}&month={$month}')">生成凭证</span>
eof;
                            $voucher = query('voucher', "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '$array[id]' and source = '结转损益'");
                            if ($voucher['id']) {
                                $btn = <<<eof
<span class="spanButton li-btn-blue-bg" onclick="newIframe('新增凭证',root+'control/adIndex.html?cla=voucherEdit&fun=home&id={$voucher['id']}')">查看凭证</span>
eof;
                            }
                            $li .= <<<eof
        <li>
             <div class="tag-contain">
                   <div class="tag-contain-title">
                         <span class="tag-contain-title-text">$array[name]</span>
                   </div>
                   <div class="tag-contain-body">
                         <ul class="tag-contain-ul">
                             <li>$money</li>
                         </ul>
                   </div>
                   <div class="tag-contain-foot">
                   </div>
                   <div class="tag-edit-content">
                         $btn
                   </div>
             </div>
        </li>
eof;
                        }

                        $html = <<<eof
    <ul class='tag-list-ul'>
        $li
    </ul>
eof;
                        break;
                    case 'third':
                        $liOption              = ['期末检查', '结转损益', '断号检查', '报表检查', '资金检查'];
                        $li                    = '';
                        $_SESSION['checkPass'] = true;
                        foreach ($liOption as $item) {
                            $li .= $this->thirdCheck($item, $month);
                        }
                        $html = <<<eof
<div class="stage-three-block">
    <ul>
        $li
    </ul>
</div>
eof;
                        break;
                    default:
                        //第一阶段
                        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and type not in ('结转损益（收入）','结转损益（费用）') order by time asc"));
                        $li  = '';
                        foreach ($all['array'] as $array) {
                            $btn     = <<<eof
<img class="left" onclick="layer('carryover','settingPage',{id:'{$array['id']}'})" alt="" src="{$this->root}img/control/setting.svg">
<span class="spanButton li-btn-blue-bg" onclick="newIframe('新增凭证',root+'control/adIndex.html?cla=voucherEdit&fun=home&method=endPeriod&month={$month}&sourceId={$array['id']}')">生成凭证</span>
eof;
                            $voucher = query('voucher', "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '$array[id]' and source = '期末结转'");
                            if ($voucher['id']) {
                                $btn = <<<eof
<span class="spanButton li-btn-blue-bg" onclick="newIframe('新增凭证',root+'control/adIndex.html?cla=voucherEdit&fun=home&id={$voucher['id']}')">查看凭证</span>
eof;
                            }

                            $li .= <<<eof
            <li>
             <div class="tag-contain">
                   <div class="tag-contain-title">
                         <span class="tag-contain-title-text">{$array['name']}</span>
                   </div>
                   <div class="tag-contain-body">
                         <ul class="tag-contain-ul">
                             <li>&nbsp;</li>
                         </ul>
                   </div>
                   <div class="tag-contain-foot">
                   </div>
                   <div class="tag-edit-content">
                         $btn
                   </div>
             </div>
            </li>
eof;

                        }
                        $html = <<<eof
    <ul class='tag-list-ul'>
        $li
    </ul>
eof;

                        break;
                }
                $json['html']  = $html;
                $json['warn']  = 2;
                $json['stage'] = $stage;
            }

        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 自动生成损益凭证
     */
    public function autoCreateIncome($month)
    {
        $rule = companyClass::returnRule(1);
        if ($rule == 'enterpriseRule'){
            $subjectCode = '4103';
        }else{
            $subjectCode = '3103';
        }
        //判断是否已生成了结转损益
        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and type in ('结转损益（收入）','结转损益（费用）') order by time asc"));
        foreach ($all['array'] as $period_end_setting) {
            $voucher            = query('voucher', "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '$period_end_setting[id]' and source = '结转损益'");
            $flag                   = false;
            if (!$voucher['id']) {
                $multObj            = new multiColumnAccountClass();
                $checkOut           = new checkoutClass();
                $voucher_word       = query('voucher_word', "coid = '" . self::$coid . "' and isDefault = '是'");
                $field              = [
                    'id'            => suiji(),
                    'coid'          => self::$coid,
                    'isTemplate'    => '否',
                    'stid'          => self::$stid,
                    'source'        => '结转损益',
                    'recordDate'    => $month . '-' . sprintf("%02d", date('t', strtotime($month . '-01'))),
                    'voucherWordId' => $voucher_word['id'],
                    'text'          => '自动'.$period_end_setting['type'],
                    'sourceId'      => $period_end_setting['id'],
                ];
                $field['voucherNo'] = voucherEditClass::voucherNo($field['voucherWordId'], $field['recordDate']);
                /********凭证明细*******/
                $index                  = 0;

                $jieTotalMoney          = $daiTotalMoney = $totalMoney=0;
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = date('m月', strtotime($month . '-01')) . '结转损益';
                    $columns = [];
                    $multObj->loopSubjectIds($array['subjectId'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject = query('subject', "id = '$subjectId'");
                        $balance = $checkOut->balanceOnlyMoney($month, $subject['id']);
                        if ($subject['direction'] == '借') {
                            $jieMoney  = 0;
                            $daiMoney  = $balance;
                            $direction = '贷';
                        } else {
                            $daiMoney  = 0;
                            $jieMoney  = $balance;
                            $direction = '借';
                        }
                        if (abs($balance) > 0 && $subject['code'] != $subjectCode) {
                            $index++;
                            $totalMoney+=$jieMoney;
                            $jieTotalMoney += $jieMoney;
                            $daiTotalMoney += $daiMoney;
                            $flag          = true;
                            $voucherPrice  = 0;
                            $voucherNum    = 0;
                            $voucherRate   = 0;
                            $collection    = [
                                'voucherPrice' => voucherEditClass::formatPrice($voucherPrice),
                                'voucherRate'  => $voucherRate,
                                'voucherMoney' => $voucherRate > 0 ? round($voucherPrice * $voucherNum / $voucherRate, 2) : 0,
                            ];
                            $mxField       = [
                                'id'          => suiji(),
                                'coid'        => self::$coid,
                                'orderId'     => $field['id'],
                                'summary'     => $summary,
                                'subjectId'   => $subject['id'],
                                'subjectName' => $subject['name'],
                                'subjectCode' => $subject['code'],
                                'direction'   => $direction,
                                'money'       => $direction == '借' ? self::yuanToCent($jieMoney) : self::yuanToCent($daiMoney),
                                'subjectAttr' => json_encode($collection, 320),
                                'voucherNum'  => voucherEditClass::formatNum($voucherNum),
                                'rowList'     => $index
                            ];
                            $warn = self::insert(['table' => 'voucher_detail', 'field' => $mxField]);
                            if ($warn !='新增成功'){
                                return '新增凭证明细失败';
                            }
                        }
                    }
                }
                if ($flag) {
                    //有明细才生成凭证
                    $subject = query('subject', "code = '$subjectCode' and coid = '" . self::$coid . "'");//本年利润科目
                    if ($jieTotalMoney > $daiTotalMoney) {
                        $jieMoney  = 0;
                        $daiMoney  = $jieTotalMoney - $daiTotalMoney;
                        $direction = '贷';
                    } else {
                        $daiMoney  = 0;
                        $jieMoney  = $daiTotalMoney - $jieTotalMoney;
                        $direction = '借';
                    }
                    $totalMoney+=$jieMoney;
                    $voucherPrice = 0;
                    $voucherNum   = 0;
                    $voucherRate  = 0;
                    $collection   = [
                        'voucherPrice' => voucherEditClass::formatPrice($voucherPrice),
                        'voucherRate'  => $voucherRate,
                        'voucherMoney' => $voucherRate > 0 ? round($voucherPrice * $voucherNum / $voucherRate, 2) : 0,
                    ];
                    $summary      = date('m月', strtotime($month . '-01')) . '结转损益';
                    $mxField      = [
                        'id'          => suiji(),
                        'coid'        => self::$coid,
                        'orderId'     => $field['id'],
                        'summary'     => $summary,
                        'subjectId'   => $subject['id'],
                        'subjectName' => $subject['name'],
                        'subjectCode' => $subject['code'],
                        'direction'   => $direction,
                        'money'       => $direction == '借' ? self::yuanToCent($jieMoney) : self::yuanToCent($daiMoney),
                        'subjectAttr' => json_encode($collection, 320),
                        'voucherNum'  => voucherEditClass::formatNum($voucherNum),
                        'rowList'     => $index + 1
                    ];
                    $warn = self::insert(['table' => 'voucher_detail', 'field' => $mxField]);
                    if ($warn !='新增成功'){
                        return '新增凭证明细失败';
                    }
                    $field['money'] = round($totalMoney,2);
                    $warn = self::insert(['table' => 'voucher', 'field' => $field]);
                    if ($warn !='新增成功'){
                        return '新增凭证失败';
                    }
                }

            }
        }
        return true;
    }


    /**
     * 计算转入的余额
     */
    public function calculateBalance($id, $month)
    {
        $rule = companyClass::returnRule(1);
        if ($rule == 'enterpriseRule'){
            $subjectCode = '4103';
        }else{
            $subjectCode = '3103';
        }
        $info    = query('period_end_setting', "id = '$id'");
        $multObj = new multiColumnAccountClass();
        $all     = find(array('table' => 'period_end_setting_detail', 'where' => "orderId = '$id' order by list asc"));
        $money   = 0;
        foreach ($all['array'] as $array) {
            $columns = [];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            foreach ($columns as $subjectId) {
                //获取与科目余额方向相反的
                $subject = query('subject', "id = '$subjectId'");
                if ($subject['code'] != $subjectCode) {
                    $balance = $this->balanceOnlyMoney($month, $subject['id']);
                    if ($info['type'] == '结转损益（费用）' && $subject['direction'] == '借') {
                        $money += $balance;
                    } elseif ($info['type'] == '结转损益（收入）' && $subject['direction'] == '贷') {
                        $money += $balance;
                    }
                }
            }
        }
        return $money;
    }

    /**
     * 判断是否已结转损益
     */
    public function juageIsEndProfitAndLoss($month): bool
    {
        //判断损益类的科目余额是否为0
//        $bool = $this->checkBalance($month, '成本类');
//        if (!$bool) {
//            return false;
//        }
        $bool = $this->checkBalance($month, '损益类');
        if (!$bool) {
            return false;
        }
        return true;
    }


    /**
     * 第三阶段审查
     */
    private function thirdCheck($type, $month): string
    {
        $pass_img    = "<img src='" . $this->pass_ico . "'>";
        $no_pass_img = "<img src='" . $this->no_pass_ico . "'>";
        $tip_img     = "<img src='" . $this->problem_ico . "'>";
        $state       = '已完成';
        switch ($type) {
            case '期末检查':
                $liItem = '';
                //现金、银行存款存在贷方余额
                $bool = $this->checkCashAndBank($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '现金银行存款存在贷方余额');
                //短期、长期借款是否有借方余额
                $bool = $this->checkShortOrLongMoney($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '短期、长期借款是否有借方余额');
                //原材料、库存商品是否有数量为零，金额不为0的情况
                $bool = $this->checkMaterial($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '原材料、库存商品有数量为零，金额不为0的情况');
                //主营业务收入和主营业务成本数量核算是否有不一致
                $bool = $this->checkMainbusiness($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '主营业务收入和主营业务成本数量核算是否有不一致');

//                $liItem .= "<li>$img<span>损益类科目的收入科目是否有借方发生额，费用类科目是否有贷方发生额</span></li>";

                //存货、原材料和库存商品是否存在红数---判断数量是否为负
                $bool = $this->checkMaterialNum($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '存货、原材料和库存商品是否存在红数');

                //检查应收账款:是否有贷方余额
                $bool = $this->shouldRec($month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '应收账款是否有贷方余额');

                //检查应付账款:是否有借方余额
                $bool = $this->shouldPay($month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '应付账款是否有借方余额');
                //检查是否已计提职工薪酬
                $bool = $this->voucherCert('计提职工薪酬', $month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '是否已计提职工薪酬');
                //检查是否已结转未交增值税
                $bool = $this->voucherCert('结转未交增值税', $month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '检查增值税是否已结转');
                //检查是否已计提职工薪酬
                $bool = $this->voucherCert('计提税金及附加', $month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '检查是否已计提费用及税金');

                //是否还有未记账的凭证
                $bool = $this->checkisRecord($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '检查是否有未记账的凭证');

                if ($state == '未通过') {
                    $_SESSION['checkPass'] = false;
                }

                $li = "<li>-期末检查：$state
                            <div class='check-block'>
                                <ul>
                                    $liItem
                                </ul>
                            </div>
                       </li>";
                break;
            case '结转损益':
                $bool = $this->checkBalance($month, '成本');
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem = $this->returnItem($img, '成本类科目是否有余额');
                $bool   = $this->checkBalance($month, '损益');
                if (!$bool) {
                    $state = '未通过';
                    $img   = $no_pass_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '损益类科目是否有余额');
                $bool   = $this->checkCostTrans($month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '是否已操作成本归集与结转');
                //判断是否已结转损益
                $bool = $this->juageIsEndProfitAndLoss($month);
                if (!$bool) {
                    $state = '未通过';
                    $img   = $no_pass_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '是否已结转当期损益');
                $li     = "<li>-结转损益：$state
                            <div class='check-block'>
                                <ul>
                                    $liItem
                                </ul>
                            </div>
                        </li>";
                break;
            case '断号检查':
                $img  = $pass_img;
                $bool = $this->checkDiscontinuous($month);
                if (!$bool) {
                    $liItem = "<li>$no_pass_img<span>存在断号</span><span class='del-row-button' style='margin-left: 20px' onclick=\"repairVoucherNo('{$month}')\">修复</span></li>";
                    $state  = '未通过';
                } else {
                    $liItem = $this->returnItem($img, '未发现断号');
                }

                $li = "<li>-断号检查：$state
                            <div class='check-block'>
                                <ul>
                                    $liItem
                                </ul>
                            </div>
                        </li>";
                break;
            case '报表检查':
                $liItem = '';

                $bool = $this->checkAsset($month);
                if (!$bool) {
                    $img   = $no_pass_img;
                    $state = '未通过';
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '资产负债表是否平衡');

                $bool = $this->checkProfit($month);
//                if (!$bool) {
//                    $img = $no_pass_img;
//                    $state = '未通过';
//                } else {
//                    $img = $pass_img;
//                }
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '资产负债表中期末“未分配利润”=利润表中“净利润”+资产负债表中“未分配利润”的年初数');

                $bool = $this->checkCash($month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '现金流量表中的“现金及现金等价物净额”=资产负债表中“货币资金”期末金额－期初金额');
//                $bool = $this->checkAsset($month);
//                if (!$bool) {
//                    $img = $no_pass_img;
//                    $state = '未通过';
//                }
//                $liItem .= "<li>$img<span>现金流量表中“支付给职工及为职工支付的现金”=资产负债表中应付职工薪酬年初余额＋本期为职工支付的工资和福利总额（包含在生产成本、制造费用、管理费用中职工薪酬）－资产负债表中应付职工薪酬期末余额</span></li>";

                $li = "<li>-报表检查：$state
                             <div class='check-block'>
                                <ul>
                                    $liItem
                                </ul>
                            </div>
                       </li>";

                break;
            case '资金检查':
                $liItem = '';
                $bool   = $this->checkFundsTotal($month);
                if (!$bool) {
                    $img = $tip_img;
                } else {
                    $img = $pass_img;
                }
                $liItem .= $this->returnItem($img, '资金总账');

                $li = "<li>-资金检查：$state
                             <div class='check-block'>
                                <ul>
                                    $liItem
                                </ul>
                            </div>
                       </li>";
                break;
            default:
                $li = '';
                break;
        }
        if ($state == '未通过') {
            $_SESSION['checkPass'] = false;
        }
        return $li;
    }

    /**
     * 检查选项
     * @param $img
     * @param $title
     * @return string
     */
    private function returnItem($img, $title): string
    {
        return "<li>$img<span>$title</span></li>";
    }

    /**
     * 核对总账
     * @param $month
     * @return bool
     */
    private function checkFundsTotal($month): bool
    {
        $timeWhere    = " and date_format(recordDate,'%Y-%m') ='$month'";
        $voucherWhere = " and date_format(a.recordDate,'%Y-%m') ='$month'";
        $all          = find(array('table' => "account", 'where' => " coid = '" . self::$coid . "' and subjectId !='' order by time asc"));
        foreach ($all['array'] as $array) {
            $subject             = query('subject', "id = '$array[subjectId]'");
            $subjectJieInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$month'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $subjectDaiInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$month'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $subjectInitMoney    = $subjectJieInitMoney - $subjectDaiInitMoney;
            if ($subject['direction'] == '借') {
                $subjectInitMoney += $subject['initMoney'];
            } else {
                $subjectInitMoney -= $subject['initMoney'];
            }
            $subjectInitMoney = self::centToYuan($subjectInitMoney);//科目期初金额
            $jieMoney         = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere . voucherClass::joinWhere(), 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $daiMoney         = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere . voucherClass::joinWhere(), 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $jieMoney         = self::centToYuan($jieMoney);
            $daiMoney         = self::centToYuan($daiMoney);
            $initMoney        = find(array('table' => 'bookkeeping', 'single' => "accountId = '$array[id]' and date_format(recordDate,'%Y-%m') < '$month'", 'field' => "ifnull(sum(income-expenses),0) as money"))['money'];
            $initMoney        += $array['initMoney'];
            $income           = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "income"));
            $out              = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "expenses"));

            if (round($subjectInitMoney - $initMoney, 2) != 0) {
                return false;
            }
            if (round($jieMoney - $income, 2) != 0) {
                return false;
            }
            if (round($daiMoney - $out, 2) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查成本归集与结转
     */
    private function checkCostTrans($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $multObj    = new multiColumnAccountClass();
        $all        = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and type in ('结转销售产品成本','结转制造费用','结转完工产品成本')"));
        foreach ($all['array'] as $array) {
            $childRes = find(array('table' => 'period_end_setting_detail', 'where' => "orderId = '$array[id]' and direction = '贷' order by list asc"));
            foreach ($childRes['array'] as $item) {
                //判断最后一级科目余额是否为0
                $columns = [];
                $multObj->loopSubjectIds($item['subjectId'], $columns);
                foreach ($columns as $subjectId) {
                    $balanceResult = $subjectObj->balance($month, $subjectId);
                    if ($balanceResult['balance'] != 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * “现金净增加额”=资产负债表中“货币资金”期末金额－期初金额
     * @param $month
     * @return bool
     */
    private function checkCash($month)
    {
        $preMonth       = date('Y-m', strtotime("-1 month", strtotime($month . '-01')));
        $assetDebt      = new assetDebtClass();
        $assetResult    = $assetDebt->balance('货币资金', $month);
        $assetPreResult = $assetDebt->balance('货币资金', $preMonth);
        $cashFlow       = new cashFlowClass();
        $all            = find(array('table' => 'cash', 'field' => "distinct type", 'where' => "coid = '" . self::$coid . "' and type != '' order by any_value(code)"));
        $monthBalance   = 0;
        foreach ($all['array'] as $index => $array) {
            $children = find(array('table' => 'cash', 'where' => "coid = '" . self::$coid . "' and type = '$array[type]' order by code"));
            foreach ($children['array'] as $item) {
                $result       = $cashFlow->balance($month, $item['id']);
                $monthBalance += $result['monthBalance'];
            }
        }
        if (round($monthBalance, 2) == round($assetResult['balance'] - $assetPreResult['balance'], 2)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 期末“未分配利润”=利润表中“净利润”+资产负债表中“未分配利润”的年初数
     */
    private function checkProfit($month): bool
    {
        $assetDebt   = new assetDebtClass();
        $result      = $assetDebt->balance('未分配利润', $month);
        $proft       = new profitIncomeClass();
        $proftResult = $proft->totalProfit('净利润', $month, companyClass::returnRule(1));
        if (round($result['balance'], 2) == round($proftResult['balance'] + $result['preBalance'], 2)) {
            return true;
        } else {
            return false;
        }
    }


    private function checkisRecord($month): bool
    {
        if (self::total(['table'=>'voucher','where'=>"coid = '".self::$coid."' and date_format(recordDate,'%Y-%m') = '$month' and workFlow !='已记账'"])>0){
            return false;
        }
        return true;
    }
    /**
     * 成本类或损益类科目是否有余额
     */
    private function checkBalance($month, $type)
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and type = '$type' and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->checkBalanceMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 成本类或损益类科目是否有余额
     */
    private function checkBalanceMx($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if ($balanceResult['balance'] != 0) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkBalanceMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 资产负债是否平衡
     * @param $month
     * @return bool
     */
    public function checkAsset($month): bool
    {
        $assetDebt = new assetDebtClass();
        $res       = $assetDebt->content($month);
        if (round($res['assetMoney'], 2) != round($res['debtMoney'], 2)) {
            return false;
        } elseif (round($res['assetInitMoney'], 2) != round($res['debtInitMoney'], 2)) {
            return false;
        }
        return true;
    }

    /**
     *
     */
    private function voucherCert($type, $month): bool
    {
        $template = query('period_end_setting', "coid = '" . self::$coid . "' and type = '$type'");
        if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and sourceId = '$template[id]' and date_format(recordDate,'%Y-%m') = '$month'")) > 0) {
            return true;
        }
        return false;
    }

    /**
     *存货、原材料和库存商品是否存在红数
     */
    private function checkMaterialNum($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1403','1405') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            if ($array['numAccount'] == '是') {
                $bool = $this->checkMaterialNumMx($array['id'], $month, $subjectObj);
                if (!$bool) {
                    return false;
                }
            }
        }
        return true;
    }

    private function checkMaterialNumMx($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if ($balanceResult['num'] < 0) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkMaterialNumMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 检查主营业务收入和主营业务成本数量核算是否有不一致
     */
    private function checkMainbusiness($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $subject    = query('subject', "coid = '" . self::$coid . "' and code ='5001' and state = '启用'");
        $recNum     = $this->childMainbuiness($subject['id'], $month, $subjectObj);
        $subject    = query('subject', "coid = '" . self::$coid . "' and code = '5401' and state = '启用'");
        $payNum     = $this->childMainbuiness($subject['id'], $month, $subjectObj);
        if ($recNum != $payNum) {
            return false;
        }

        return true;
    }

    /**
     *
     * @param $pid
     * @param $month
     * @param $subjectObj
     * @return float
     */
    private function childMainbuiness($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            return $balanceResult['num'];
        }
        $num = 0;
        foreach ($all['array'] as $array) {
            $num += $this->childMainbuiness($array['id'], $month, $subjectObj);
        }
        return $num;
    }


    /**
     * 判断凭证号是否连续
     */
    private function checkDiscontinuous($month): bool
    {
        $all = find(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and isTemplate = '否' order by any_value(voucherNo) asc", 'field' => "distinct voucherWordId"));
        foreach ($all['array'] as $array) {
            //取最大的凭证号
            $first = query('voucher', "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month'  order by voucherNo asc");
            $firstNo = $first['voucherNo'] ?: 1;
            $max = query('voucher', "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month'  order by voucherNo desc");
            $maxNo = $max['voucherNo'];
            for ($i = $firstNo; $i <= $maxNo; $i++) {
                if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month' and voucherNo = '$i'")) == 0) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 检查应收账款是否存在贷方余额
     */
    private function shouldRec($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1122') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '贷');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查应付账款是否存在借方余额
     */
    private function shouldPay($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('2202') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '借');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查原材料、库存商品有数量为零，金额不为0的情况
     * @param $month
     * @return bool
     */
    private function checkMaterial($month)
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1403','1405') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            if ($array['numAccount'] == '是') {
                $bool = $this->checkNum($array['id'], $month, $subjectObj);
                if (!$bool) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 判断库存商品，原材料数量为零，金额不为0
     * @param $pid
     * @param $month
     * @param $subjectObj
     * @return bool|null
     */
    private function checkNum($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if (($balanceResult['balance'] == 0 && $balanceResult['num'] != 0) || ($balanceResult['balance'] != 0 && $balanceResult['num'] == 0)) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkNum($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 检查短期、长期借款是否有借方余额
     * @param $month
     * @return bool
     */
    private function checkShortOrLongMoney($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('2001','2501') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '借');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 现金、银行存款存在贷方余额检查
     * @param $month
     * @return bool
     */
    private function checkCashAndBank($month): bool
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1001','1002') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '贷');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param $pid
     * @param $month
     * @param $direction
     * @return bool|null
     */
    private function findBlance($pid, $month, $direction): ?bool
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balance = $this->balanceOnlyMoney($month, $pid);
            if ($direction == '借' && $balance > 0) {
                //判断是否有借方余额
                return false;
            } elseif ($direction == '贷' && $balance < 0) {
                //判断是否有贷方余额
                return false;
            }
            return true;
        }
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, $direction);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    public function balanceOnlyMoney($month, $subjectId)
    {
        $subject = query('subject', "id = '$subjectId'");
        if (empty($subject['id'])) {
            return 0;
        }
        //期初金额
        $initMoney = $subject['initMoney'] ?: 0;
        $jieInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        $daiInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
        } else {
            $daiInit['money'] += $initMoney;
        }
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            return round($jieInit['money'] - $daiInit['money'], 2);
        } else {
            return round($daiInit['money'] - $jieInit['money'], 2);
        }
    }

    /**
     * 反结账
     * @return false|string
     */
    public function reCheckOut()
    {
        $month = $this->post('month');
        $info  = query('checkout', "coid = '" . self::$coid . "' and month = '$month'");
        if (empty($month)) {
            $json['warn'] = '未找到结账月份';
        } elseif (empty($info['id'])) {
            $json['warn'] = '此月份没有结账的数据';
        } else {
            $warn = delete(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "' and month >= '$month'"));
            if ($warn == '删除成功') {
                //添加日志
                $text = $this->control['name'] . "反结账了" . $month . " 的数据";
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '反结账成功';
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=checkout&fun=antiCheckout";
            } else {
                $json['warn'] = '反结账失败';
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 结账
     */
    public function billEnd()
    {
        $field   = [
            'month' => $this->post('month')
        ];
        $company = query('company', "coid = '" . self::$coid . "'");
        if (empty($field['month'])) {
            $json['warn'] = '未找到结账月份';
        } elseif ($company['startDate'] > $field['month']) {
            $json['warn'] = '结账日期小于账套启用日期';
        } elseif ($field['month'] > date('Y-m')) {
            $json['warn'] = '结账日期大于当前月份';
        } elseif (!isset($_SESSION['checkPass']) || !$_SESSION['checkPass']) {
            $json['warn'] = '存在未通过的检查，无法结账';
        } elseif (static::total(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "' and month = '$field[month]'")) > 0) {
            $json['warn'] = '当前月份已结账，无需重复结账';
        } else {
            $field        = array_merge($field, [
                'id'   => suiji(),
                'coid' => self::$coid,
                'stid' => self::$stid
            ]);
            $json['warn'] = static::insert(array(
                'table' => 'checkout',
                'field' => $field
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = $this->control['name'] . "结账了" . $field['month'] . " 的数据";
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '结账成功';
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=checkout&fun=home";
            }

        }

        return json_encode($json, 320);
    }

    private function settingStyle(): string
    {
        return <<<eof
<style>
.check-block{padding-left: 20px}
.check-block>ul>li>img{width: 20px;height: 20px;vertical-align: text-top;}
.check-block>ul>li>span{margin-left: 5px}
.stage-three-block{margin-top: 10px}
.stage-three-block ul li{padding: 5px}
.hide{display: none !important;}
.setting-content{padding: 10px;margin-top: 10px;max-height: 650px;overflow-y: auto;}
.progress-li-line{width: 200px;border-top: 1px solid #629AFD;margin-top: 20px}
.now-li{background-color: #629AFD;color: white !important;}
.progress-li{width: 40px;height: 40px;border: 1px solid #629AFD;line-height: 40px;text-align: center;border-radius: 50%;color: #629AFD}
.progress-text{position: absolute;white-space: nowrap;margin-top: 5px}
.progress-content{display: flex;flex-direction: row;padding: 20px}
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 258px;height: 130px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{padding: 10px;}
.tag-contain-ul li{padding: 5px 20px 0 20px;font-size: 16px;font-weight: bold}
.tag-contain-foot{padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-edit-content .spanButton{float: right}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer;margin-top: 10px}
.label-edit-ul li{float: left}
.add-attr-button{border: 2px solid #6aacfb;margin-top: 5px;color: #6aacfb;font-weight: bold;font-size: 21px; width: 16px;height: 16px;text-align: center;line-height: 13px;cursor: pointer;border-radius: 2px;
</style>
eof;

    }

    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.dot{display: inline-block;width: 20px;height: 20px;border-radius: 50%;vertical-align: text-bottom;}

.to-left{margin-left: 50px}
.period-content{padding: 10px 0}
.year-font{font-weight: 700;font-size: 20px}
.period-content-year{padding: 10px 0}
.row-item-ul{display: flex;flex-direction: row;justify-content: flex-start;margin-top: 10px;cursor: pointer}
.row-item-ul .row-item{width: 100px;height: 90px;border: 1px solid rgba(98, 154, 253, 1);border-radius: 4px;margin-right: 15px}
.row-item-top{height: 28px;background-color: rgba(98, 154, 253, 1)}
.row-item-bottom{text-align: center;line-height: 60px;font-weight:700}
.yellow{background-color: #F59A23}
.yellow-border{border-color: #F59A23 !important;}
.gray{background-color: #D7D7D7}
.gray-border{border-color: #D7D7D7 !important;}
.blue{background-color: #629AFD}
.blue-border{border-color: #629AFD !important;}
</style>
eof;

    }

    /*列表-查询条件*/
    public function antiCheckout($workFlow = '反结账')
    {
        return $this->homeFun($this->homeForm('反结账'));
    }

    public function antiCheckoutSearch()
    {

        $preYear = '';//上一年
        $content = '';
        $months  = [];
        $all     = find(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "' order by month desc"));
        foreach ($all['array'] as $k => $array) {
            $months[] = $array['month'];
        }
//        $months = array_reverse($months);
        foreach ($months as $k => $val) {
            $month           = date("Y-m", strtotime($val . '-01'));
            $monthText       = date("m月", strtotime($val . '-01'));//当前月份
            $year            = date("Y", strtotime($val . '-01'));//当前年份
            $borderClass     = 'gray-border';
            $backgroundClass = 'gray';
            if (empty($preYear) || $preYear != $year) {
                $content .= <<<eof
            <div class="period-content-year">
                <div><p><span class="year-font">{$year}年</span></p></div>
                <div class="row-item-ul">
eof;
            }
            $content .= <<<eof
                <div class="end-item row-item $borderClass" data-month="$month">
                    <div class="row-item-top $backgroundClass"></div>
                    <div class="row-item-bottom">$monthText</div>
                </div>
eof;
            if (isset($months[$k + 1]) && $year != date('Y', strtotime($months[$k + 1] . '-01'))) {
                $content .= <<<eof
                 </div>
                </div>
eof;
            }
            $preYear = $year;
        }
        $json['html'] = <<<efo
<div style="padding: 0 10px">
    <div class="period-content">
        $content
    </div>
</div>
<script>
$(".end-item").on('click',function() {
   
    let month = $(this).data('month');
    if (!month){
        msg('未找到月份','error');
    }else{
        cxDialog('确定进行反结账?', () => {
          $.post(root+'control/adIndex.html?cla=checkout&fun=reCheckOut',{month:month},function(res) {
                     if (res.warn==2){
                         location.href = res.href;
                     }else{
                         msg(res.warn,'error');
                     }
                  },'json')
        }, () => {
          // click no callback
        });
            }
        })
</script>
efo;
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, customizeForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=customize',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 是否已结账
     * @param $date
     * @return bool
     */
    public static function isChecked($date): bool
    {
        //获取最新结账日期
        $checkout = query('checkout', "coid = '" . self::$coid . "' order by month desc");
        if (date('Y-m', strtotime($date)) <= $checkout['month']) {
            return true;
        } else {
            return false;
        }
    }

}
